#ifndef MAIN_CPP
#define MAIN_CPP

using namespace std;

#include "songtree.h"
#include "cdgsettings.h"
#include "songhandler.h"
#include "dbcheck.h"

#include <mythtv/mythcontext.h>
#include <mythtv/mythdbcon.h>
#include <mythtv/lcddevice.h>
#include <mythtv/libmythui/myththemedmenu.h>


void CDGCallback(void *data, QString &selection)
{
    (void)data;

    QString sel = selection.lower();

    // Configuration: General setting
    if (sel == "cdg_settings")
    {   
        cerr << "setting" <<endl;
         MythCDGGeneralSettings settings;
         settings.exec();
    }

    // Configuration: Search for songs
    if (sel == "cdg_search")
    {
        SongHandler::processAllSongs();
    }

    // Configuration: Clear all song info in DB
    if (sel == "cdg_clear_data")
    {
        SongHandler::clearAllSongData();
    }

}

void runMenu(QString which_menu)
{
    QString themedir = gContext->GetThemeDir();

    MythThemedMenu *diag = new MythThemedMenu(themedir.ascii(), which_menu,
                                              GetMythMainWindow()->GetMainStack(), 
                                              "cdg menu");

    diag->setCallback(CDGCallback, NULL);
    diag->setKillable();

    if (diag->foundTheme())
    {
        if (class LCD * lcd = LCD::Get())
        {
            lcd->switchToTime();
        }
        GetMythMainWindow()->GetMainStack()->AddScreen(diag);
    }
    else
    {
        cerr << "Couldn't find theme " << themedir << endl;
        delete diag;
    }
}

extern "C" {
    int mythplugin_init(const char *libversion);
    int mythplugin_run(void);
    int mythplugin_config(void);
}


void setupKeys(void)
{
    REG_KEY("CDG", "FFWD",       "Fast forward",               "PgDown");
    REG_KEY("CDG", "RWND",       "Rewind",                     "PgUp");
    REG_KEY("CDG", "PAUSE",      "Pause/Start playback",       "P");
    REG_KEY("CDG", "STOP",       "Stop playback",              "O");
}

int mythplugin_init(const char *libversion)
{
    if (!gContext->TestPopupVersion("mythcdg", libversion, MYTH_BINARY_VERSION))
        return -1;
    
    gContext->ActivateSettingsCache(false);
    if (!UpgradeCDGDatabaseSchema())
    {
        VERBOSE(VB_IMPORTANT,
                "Couldn't upgrade database to new schema, exiting.");
        return -1;
    }
    gContext->ActivateSettingsCache(true);
    
    MythCDGGeneralSettings settings;
    settings.load();
    settings.save();

    setupKeys();

    return 0;
}

int mythplugin_run (void)
{
    gContext->addCurrentLocation("mythcdg");

    SongTree dialog(gContext->GetMainWindow(), "cdgtree", "cdg-");
    dialog.exec();

    gContext->removeCurrentLocation();

    return 1;
}

int mythplugin_config (void) 
{
    runMenu("cdg_settings.xml");
    return 0;
}

#endif
